
import chatLogic
from whiff.middleware import misc
from whiff import resolver
from whiff import whiffenv
import Cookie
import urllib

errorkey = "whiff.chat.login_error"

class SetNick(misc.utility):
    def __init__(self, page, elsePage, **bogus):
        if bogus:
            #pr "bogus", bogus
            raise ValueError, "bogus parameters"
        self.page = page
        self.elsePage = elsePage
    def __call__(self, env, start_response):
        my_start_response = start_response
        env = resolver.process_cgi(env)
        cgi_dict = env[whiffenv.CGI_DICTIONARY]
        nicknames = cgi_dict.get("MessageInNickname")
        #pr "found nicknames", nicknames
        if nicknames and ("&" in nicknames[0] or nicknames[0]=="X"):
            env[errorkey] = "invalid nickname, please choose another"
        elif nicknames:
            nickname = nicknames[0]
            #connection = chatLogic.test_gadfly_connection(whiffenv.getId(env, "DbPrefix"))
            connection = chatLogic.getConnection(env)
            nickname = nickname.strip()[:20]
            if nickname and not connection.validateNick(nickname):
                # nickname is new... insert a new speaker with that nick.
                connection.addSpeaker(nickname, "new user")
                connection.commit()
                # put the nickname in a cookie...
                def my_start_response(status, headers):
                    my_headers = headers[:]
                    cookieName = chatLogic.cookieName(env)
                    c = Cookie.SimpleCookie()
                    c[cookieName] = urllib.quote(nickname)
                    cookieheader = str(c)+"; path=/"
                    #cookietext = "%s=%s; path=/" % (cookieName, nickname)
                    #pr "calculated cookie", repr(cookieheader)
                    cs = cookieheader.split(":")
                    cookietext = cs[1].strip()
                    #pr "setting cookie", cookietext
                    my_headers.append( ('Set-Cookie', str(cookietext)) )
                    #pr "sending headers", my_headers
                    start_response(status, my_headers)
                # return the success page
                #pr "returning success"
                variable = whiffenv.getName(env, ".nick")
                env[variable] = nickname
                return self.deliver_page(self.page, env, my_start_response)
            else:
                #pr "nickname", repr(nickname), "not available"
                env[errorkey] = repr(nickname)+" is not available, sorry."
        else:
            #pr "no nickname found"
            env[errorkey] = "Please choose a nickname."
        # otherwise send the else page
        #pr "delivering login page"
        return self.deliver_page(self.elsePage, env, my_start_response)

__middleware__ = SetNick
